<?php
//Start session
if (!isset($_SESSION))
{
    session_start();
}

require_once("includes/db_connect.php");

$errmsg_arr = array();

$errflag = false;

$username = clean($_POST['username']);
$password = clean($_POST['password']);

if($username == '')
{
    //$errmsg_arr[] = "Username missing";
    $errflag = true;
}

if($password == '')
{
    //$errmsg_arr[] = "Password missing";
    $errflag = true;
}

if($errflag)
{
    $_SESSION['LOGIN_ERR'] = "Login information missing";
    session_write_close();
    header("location: login.php");
    exit();
}

$passwordhash = md5($password);
$sql = "SELECT * FROM dkp_users WHERE username='$username' AND password='$passwordhash'";
$result = mysql_query($sql);

if($result)
{
    if(mysql_num_rows($result) == 1)
    {
        session_regenerate_id();
        $user = mysql_fetch_assoc($result);
        
        if(isset($_POST['autologin']))
        {
            setcookie("username", $user['username'], time() + 31536000);
            setcookie("password", $user['password'], time() + 31536000);
        }

        $_SESSION['SESS_USER_ID'] = $user['userid'];
        $_SESSION['SESS_USER_NAME'] = $user['username'];
        session_write_close();



        header("location: admin/admin.php");
        exit();
    }
    else
    {
        $_SESSION['LOGIN_ERR'] = "Login failed, please double check login information";
        session_write_close();
        header("location: login.php");
        exit();
    }
}
else
{
    die("Query failed " . mysql_error());
}

?>